package sunsun.xiaoli.jiarebang.device.pondteam;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.pondteam.R;
import com.itboye.pondteam.base.BaseActivity;
import com.itboye.pondteam.bean.DeviceDetailModel;
import com.itboye.pondteam.custom.CustomCircleProgress;
import com.itboye.pondteam.custom.wheelview.view.WheelPicker;
import com.itboye.pondteam.presenter.UserPresenter;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.volley.ResultEntity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import sunsun.xiaoli.jiarebang.BuildConfig;
import sunsun.xiaoli.jiarebang.app.App;
import sunsun.xiaoli.jiarebang.utils.ComparePondFilterVersion;

import static com.itboye.pondteam.utils.ColoTextUtil.setColorfulValue;
import static sunsun.xiaoli.jiarebang.utils.ComparePondFilterVersion.changeHostOrPort;


/**
 * Created by Administrator on 2017/3/7.
 */
public class ActivityShouDong extends BaseActivity implements Observer {
    ImageView img_back;
    CustomCircleProgress circleProgress;
    String title;
    TextView txt_title;
    //    DeviceDetailModel model;
    TextView status;
    TextView once_again;
    TextView txt_was_time;
    RelativeLayout re_single_time_setting;
    UserPresenter userPresenter;
    App myApp;
    private int totalCount;
    private AlertDialog mAlertDialog;
    private String did;
    public long requestTime;
    private String tempStatus = "0";
    private DeviceDetailModel deviceDetailModelForTCP;
    private String wash_status;
    private String clean_times = "clean_times";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shoudong);
        myApp = (App) getApplication();
        myApp.shoudongUI = this;
        circleProgress.setStatus(CustomCircleProgress.Status.INIT);//初始化状态
        circleProgress.setProgress(0);
        title = getIntent().getStringExtra("title");
        txt_title.setText(title);
        userPresenter = new UserPresenter(this);
        if (BuildConfig.APP_TYPE.equalsIgnoreCase("pondteam".toLowerCase())) {
            changeHostOrPort(myApp.pondDeviceDetailUI.deviceDetailModel.getVer(), userPresenter, null, ComparePondFilterVersion.isTrue(myApp.pondDeviceDetailUI.deviceDetailModel.getVer()));
        }
        if (myApp.pondDeviceDetailUI != null) {
            did = myApp.pondDeviceDetailUI.did;
        }

        getClState();
        if (tempStatus.equalsIgnoreCase("1") || tempStatus.equalsIgnoreCase("2")) {
            progress = Integer.parseInt(deviceDetailModelForTCP.getCl_sche());
        } else {
            progress = 0;
        }
        setShouDongData();
    }

    public void getClState() {
        if (myApp.pondDeviceDetailUI != null) {
            deviceDetailModelForTCP = myApp.pondDeviceDetailUI.deviceDetailModel;
        }
        tempStatus = deviceDetailModelForTCP.getCl_state();
        mNewTempValue = deviceDetailModelForTCP.getCl_dur();
    }

    //        int pro;
    public void setShouDongData() {
        once_again.setVisibility(View.GONE);
        String wash_status = "";
        if (deviceDetailModelForTCP != null) {
            if (deviceDetailModelForTCP.getCl_state() != null) {
                if (tempStatus.equals("0")) {
                    wash_status = getString(R.string.current_status) + getString(R.string.readytoclean);
                    circleProgress.setStatus(CustomCircleProgress.Status.INIT);
                } else if (tempStatus.equals("1")) {
                    wash_status = getString(R.string.current_status) + getString(R.string.washing);
                    circleProgress.setStatus(CustomCircleProgress.Status.Starting);
                    startProgressThread();
                } else if (tempStatus.equals("2")) {
                    circleProgress.setStatus(CustomCircleProgress.Status.Pause);
                    wash_status = getString(R.string.current_status) + getString(R.string.pause_washing);
                    circleProgress.setProgress(progress);
                    removeProgressThread();
                } else if (tempStatus.equals("3")) {
                    wash_status = getString(R.string.current_status) + getString(R.string.problem);
                    circleProgress.setStatus(CustomCircleProgress.Status.End);
                    once_again.setVisibility(View.VISIBLE);
                    removeProgressThread();
                }
                setItsColor(wash_status);
            }
            txt_was_time.setText(deviceDetailModelForTCP.getCl_dur() + getString(R.string.seconds));
            txt_was_time.setTag(deviceDetailModelForTCP.getCl_dur());
            totalCount = deviceDetailModelForTCP.getCl_dur();
            circleProgress.setMax(totalCount);
            System.out.println("pro" + circleProgress.getProgress() + "::" + Integer.parseInt(deviceDetailModelForTCP.getCl_sche()));
//            if (circleProgress.getStatus() == CustomCircleProgress.Status.Starting) {
//                circleProgress.setProgress(Integer.parseInt(deviceDetailModelForTCP.getCl_sche()));
//            } else if (circleProgress.getStatus() == CustomCircleProgress.Status.Pause) {
//                circleProgress.setProgress(Integer.parseInt(deviceDetailModelForTCP.getCl_sche()));
//            }
        }
    }

    private void startProgressThread() {
        new Thread(runnable).start();
    }

    private void removeProgressThread() {
        try {
            handler.removeCallbacks(runnable);
        } catch (Exception e) {

        }
    }


    private void setItsColor(String wash_status) {
        int startPo = getString(R.string.current_status).length();
        int stopPo = wash_status.length();
        setColorfulValue(startPo, stopPo, R.color.main_green, wash_status, status);
    }

    int mNewTempValue = 0;

    private void isConnect() {
        if (myApp.pondDeviceDetailUI != null) {
            if (!myApp.pondDeviceDetailUI.isConnect) {
                MAlert.alert(getString(R.string.disconnect));
                return;
            }
        }

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.img_back) {
            finish();

        } else if (i == R.id.circleProgress) {
            isConnect();
            wash_status = "";
            if (circleProgress.getStatus() == CustomCircleProgress.Status.Starting) {
                wash_status = "2";
                //如果是开始状态点击则变成关闭暂停状态
            } else {
                wash_status = "1";
            }
            userPresenter.deviceSet(did, -1,null, null, "", -1, "", "", wash_status, "", "", "", "", "", "", -1, -1, "", "", "", "", -1, -1, "");
        } else if (i == R.id.re_single_time_setting || i == R.id.txt_was_time) {
            isConnect();
            if (circleProgress.getStatus() == CustomCircleProgress.Status.Starting || circleProgress.getStatus() == CustomCircleProgress.Status.Pause) {
                //正在清洗中
                MAlert.alert(getString(R.string.device) + getString(R.string.washing));
                return;
            }
            showTimePeroid();
        }

    }


    List<String> list = new ArrayList<>();

    private void showTimePeroid() {
        if (myApp.pondDeviceDetailUI != null) {
            mNewTempValue = myApp.pondDeviceDetailUI.detailModelTcp.getCl_dur();
        }
        View view = LayoutInflater.from(this).inflate(R.layout.alertdialog_number, null);
        WheelPicker myNumberPickerView = view.findViewById(R.id.number_picker1);
        list = Arrays.asList(getResources().getStringArray(R.array.timeArray));
        int position = list.indexOf(mNewTempValue + "");
        myNumberPickerView.setData(list);
        myNumberPickerView.setSelectedItemPosition(position == -1 ? 0 : position);
        android.support.v7.app.AlertDialog.Builder alert = new android.support.v7.app.AlertDialog.Builder(this);
        alert.setPositiveButton(getString(R.string.ok), (dialog, which) -> userPresenter.deviceSet(did, -1,null, null, "", -1, "", mNewTempValue + "", "", "", "", "", "", "", "", -1, -1, "", "", "", "", -1, -1, clean_times));
        alert.setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
        });
        myNumberPickerView.setOnItemSelectedListener((picker, data, position1) -> mNewTempValue = Integer.valueOf(data + ""));
        alert.setView(view);
        alert.create();
        alert.show();
    }

    @Override
    protected void onDestroy() {
        myApp.shoudongUI = null;
        removeProgressThread();
        super.onDestroy();
    }

    private int progress;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String wash_status = "";
            switch (msg.what) {
                case PROGRESS_CIRCLE_STARTING:
//                    progress = Integer.parseInt(myApp.pondDeviceDetailUI.deviceDetailModel.getCl_sche());
                    progress += 1;
                    circleProgress.setProgress(progress);
                    if (progress >= totalCount) {
                        wash_status = getString(R.string.current_status) + getString(R.string.finish_washing);
                        handler.removeMessages(PROGRESS_CIRCLE_STARTING);
                        progress = 0;
                        circleProgress.setProgress(0);
                        circleProgress.setStatus(CustomCircleProgress.Status.End);//修改显示状态为完成
                    } else {
                        wash_status = getString(R.string.current_status) + getString(R.string.washing);
                        //延迟100ms后继续发消息，实现循环，直到progress=100
                        handler.postDelayed(runnable, 1000);
                    }
                    setItsColor(wash_status);
                    break;
            }
        }
    };

    Runnable runnable = () -> {
        Message message = new Message();
        message.what = PROGRESS_CIRCLE_STARTING;
        handler.sendMessage(message);
    };

    public static final int PROGRESS_CIRCLE_STARTING = 0x110;

    @Override
    public void update(Observable o, Object data) {
        ResultEntity resultEntity = handlerError(data);
        if (resultEntity != null) {
            if (resultEntity.getCode() != 0) {
                MAlert.alert(resultEntity.getMsg());
                return;
            }
            if (resultEntity.getEventType() == UserPresenter.deviceSet_success) {
                MAlert.alert(resultEntity.getData());
                requestTime = System.currentTimeMillis();
                tempStatus = wash_status;
                setShouDongData();
            } else if (resultEntity.getEventType() == UserPresenter.deviceSet_fail) {
                MAlert.alert(resultEntity.getData());
                requestTime = System.currentTimeMillis();
            } else if (resultEntity.getEventType() == clean_times) {
                MAlert.alert(resultEntity.getData());
                requestTime = System.currentTimeMillis();
                txt_was_time.setText(mNewTempValue + getString(R.string.seconds));
                txt_was_time.setTag(mNewTempValue);
            }
        }

    }
}
